<?php

namespace app\api\controller;

use app\api\service\PlanService;
use app\api\validate\PlanValidate;
use common\controller\TokenController;


class Plan extends TokenController
{

    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * @return \think\response\Json
     */
    public function getInfo()
    {
        $input_rulr = [
            'plan_id' => '',
        ];
        $get = input_extract_rule($input_rulr, 'get');
        PlanValidate::instance()->runCheck($get,'',__FUNCTION__);
        $ret = PlanService::instance()->getInfo($get);
        return $this->json_responce(['plan' => $ret]);
    }

    public function getList()
    {
        $input_rulr = [
            'finish_time' => $_SERVER['REQUEST_TIME'],
        ];
        $get = input_extract_rule($input_rulr, 'get');
        $ret = PlanService::instance()->getList($get);
        return $this->json_responce(['list' => $ret]);
    }

    public function save()
    {
        $input_rulr = [
            'content' => '',
            'cycle' => '',
            'plan_id' => '',
        ];
        $post = input_extract_rule($input_rulr, 'post');
        $ret = PlanService::instance()->save($post);
        return $this->json_responce();
    }

    public function delete()
    {
        $input_rulr = [
             'plan_id' => '',
        ];
        $post = input_extract_rule($input_rulr, 'post');
        PlanService::instance()->delete($post);
        return $this->json_responce();

    }

    public function finish($plan_id)
    {
        $input_rulr = [
             'plan_id' => '',
        ];
        $post = input_extract_rule($input_rulr, 'post');
        $ret = PlanService::instance()->finish($post);
        return $this->json_responce();
    }

    /**
     * 统计
     * @return type
     */
    public function plan_stats()
    {
        $start_date = "";
        $end_date = "";
        $date = date("Y-m-d H:i:s");
        if (input('date', 5) == 6) {
            $timestamp = strtotime('-1 month');
            $date = date("Y-m-d H:i:s", $timestamp);
        }
        list($start_date, $end_date) = get_the_month($date);
        $year = to_date($start_date, "Y");
        $month = to_date($start_date, "n");
        $where = [
            ['member_id', '=', $this->user_id,],
        ];
        $cout_daily = PlanService::count_daily($where, $start_date, $end_date);
        $cout_year = PlanService::count_year($where, $year);
        $this->assign(compact([
            'cout_daily',
            'cout_year',
            'year',
            'month',
        ]));
        $list_html = $this->fetch('plan_stats');
        $this->assign('list_html', $list_html);
        if ($this->request->isAjax()) {
            return $list_html;
        } else {
            return $this->fetch('plan_list_base');
        }
    }
}
